﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows;  

namespace ScrumMagic
{
    static public class DBController
    {
        private static SqlConnection mainConnection;
        static DBController()
        {
            try
            {
                // open connection to DB, ConnectionString is a property, which can be set in Settings.settings or app.config
                mainConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                mainConnection.Open(); 
            }
            catch(Exception ex)
            {
              MessageBox.Show ("Can't open database. Check connection string in config file. " + "\r\n \r\n" + ex.Message, 
                "ScrumMagic", 
                MessageBoxButton.OK);
            }
        }

        // use this property anywhere
        public static SqlConnection MainConnection
        {
            get { return mainConnection; }
        }

        public static DataTable ExecuteDataTable(SqlCommand command)
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {
                DataTable table = new DataTable();
                adapter.Fill(table);
                return table;
            }
        }

        public static DataRow ExecuteDataRow(SqlCommand command)
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {
                DataTable table = new DataTable();
                adapter.Fill(table);
                if(table.Rows.Count != 1)
                    throw new Exception("Sql Command returned not 1 record");

                return table.Rows[0];
            }
        }
    }
}
